package com.action.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.business.user.UserInfoBus;
import com.config.SystemGlobals;
import com.util.MD5;

public class Login extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String contentType = SystemGlobals.getValue("contentType");
		PrintWriter out = response.getWriter();
		response.setContentType(contentType);
		String userName = request.getParameter("username");
		String passwordF= request.getParameter("password");
		String code = request.getParameter("authencode");
		String isCookie=request.getParameter("isCookie");
		HttpSession session = request.getSession();
		String password = new MD5().getMD5ofStr(passwordF);
		UserInfoBus uib = new UserInfoBus();
		if (uib.checkLogin(userName, password)) {
			String AuthenCode = (String) request.getSession().getAttribute(
					"AuthenCode");
			if (!code.equals(AuthenCode)) {
				out
						.print("<script>alert(\"验证码有误或超时\");history.back(-1);</script>"); 
			}else {
				if(isCookie!=null&&isCookie.equals("1")){
					Cookie cookie =new Cookie("loginuser@sgblog.com",userName);
					Cookie cookie2=new Cookie("loginuserpwd@sgblog.com",passwordF);
					cookie.setMaxAge(2*7*24*60*60);
					cookie2.setMaxAge(2*7*24*60*60);
					response.addCookie(cookie);
					response.addCookie(cookie2);
				}
				session.setAttribute("login_user", userName);
				session.setAttribute("password",passwordF);
				//System.out.println((String)session.getAttribute("password"));
				response.sendRedirect(request.getContextPath()+"/blog/"+userName);
			
			}
		}

		else {
			out
					.println("<script>alert(\"您输入的用户名或密码有误\");history.back(-1);</script>");
			out.close();
		}
	}

}
